package com.ruoyi.web.controller.work;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.work.domain.WorkClient;
import com.ruoyi.work.domain.WorkPaper;
import com.ruoyi.work.service.IWorkClientService;
import com.ruoyi.work.service.IWorkPaperService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.work.domain.WorkRequestFund;
import com.ruoyi.work.service.IWorkRequestFundService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 我的请款Controller
 *
 * @author ruoyi
 * @date 2021-12-23
 */
@Controller
@RequestMapping("/work/fund")
public class WorkRequestFundController extends BaseController {
    private String prefix = "work/fund";

    @Autowired
    private IWorkRequestFundService workRequestFundService;
    @Autowired
    private IWorkPaperService workPaperService;
    @Autowired
    private IWorkClientService workClientService;


    @RequiresPermissions("work:fund:view")
    @GetMapping()
    public String fund() {
        return prefix + "/fund";
    }

    /**
     * 查询我的请款列表
     */
    @RequiresPermissions("work:fund:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WorkRequestFund workRequestFund) {
        startPage();
        List<WorkRequestFund> list = workRequestFundService.selectWorkRequestFundList(workRequestFund);
        return getDataTable(list);
    }

    /**
     * 导出我的请款列表
     */
    @RequiresPermissions("work:fund:export")
    @Log(title = "我的请款", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WorkRequestFund workRequestFund) {
        List<WorkRequestFund> list = workRequestFundService.selectWorkRequestFundList(workRequestFund);
        ExcelUtil<WorkRequestFund> util = new ExcelUtil<WorkRequestFund>(WorkRequestFund.class);
        return util.exportExcel(list, "我的请款数据");
    }

    /**
     * 新增我的请款
     */
/*    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }*/
    @GetMapping("/add/{ids}")
    public String add(@PathVariable String ids, ModelMap mmap) {
        List<WorkPaper> paperList = workPaperService.selectWorkPaperByPaperIds(ids.split(","));
        BigDecimal sum = paperList.stream().map(p -> p.getActualCost()).reduce(BigDecimal.ZERO, BigDecimal::add);
        WorkClient client = workClientService.selectWorkClientByClientId(paperList.stream().map(WorkPaper::getContactId).findFirst().get());
        WorkRequestFund workRequestFund = new WorkRequestFund();
        workRequestFund.setContactId(client.getClientId());
        workRequestFund.setContacts(client.getClientName());
        workRequestFund.setBankAccount(client.getBankAccount());
        workRequestFund.setBankName(client.getBankName());
        workRequestFund.setFundAmount(sum);
        workRequestFund.setPapers(ids);
        mmap.put("workRequestFund", workRequestFund);
        return prefix + "/add";
    }

    /**
     * 修改我的请款
     */
    @GetMapping("/look/{requestId}")
    public String look(@PathVariable("requestId") Long requestId, ModelMap mmap) {
        WorkRequestFund workRequestFund = workRequestFundService.selectWorkRequestFundByRequestId(requestId);
        mmap.put("workRequestFund", workRequestFund);
        return prefix + "/look";
    }

    /**
     * 新增保存我的请款
     */
    @RequiresPermissions("work:fund:add")
    @Log(title = "我的请款", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WorkRequestFund workRequestFund) {
        WorkClient client = workClientService.selectWorkClientByClientId(workRequestFund.getContactId());

        workRequestFund.setContactId(client.getClientId());
        workRequestFund.setContacts(client.getClientName());
        workRequestFund.setBankAccount(client.getBankAccount());
        workRequestFund.setBankName(client.getBankName());
        workRequestFund.setRequestBy(getUserName());
        workRequestFund.setRequestTime(DateUtils.getNowDate());
        workRequestFund.setCreateBy(getLoginName());
        workRequestFundService.insertWorkRequestFund(workRequestFund);

        workPaperService.selectWorkPaperByPaperIds(workRequestFund.getPapers().split(",")).forEach(
                p -> {
                    p.setRequestId(workRequestFund.getRequestId());
                    workPaperService.updateWorkPaper(p);
                }
        );


        return AjaxResult.success(workRequestFund.getRequestId());
    }

    /**
     * 修改我的请款
     */
    @RequiresPermissions("work:fund:edit")
    @GetMapping("/edit/{requestId}")
    public String edit(@PathVariable("requestId") Long requestId, ModelMap mmap) {
        WorkRequestFund workRequestFund = workRequestFundService.selectWorkRequestFundByRequestId(requestId);
        mmap.put("workRequestFund", workRequestFund);
        return prefix + "/edit";
    }

    /**
     * 修改保存我的请款
     */
    @RequiresPermissions("work:fund:edit")
    @Log(title = "我的请款", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WorkRequestFund workRequestFund) {
        return toAjax(workRequestFundService.updateWorkRequestFund(workRequestFund));
    }

    /**
     * 打回我的请款
     */
    @RequiresPermissions("work:fund:remove")
    @Log(title = "我的请款", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            String[] requestIds = Convert.toStrArray(ids);
            List<WorkRequestFund> list = workRequestFundService.selectWorkRequestFundByRequestIds(requestIds);
            if (list.stream().anyMatch(r -> !r.getRequestStatus().equals("1"))) {
                return AjaxResult.error("必须为已请款状态才能打回重审");
            }


            workPaperService.updateWorkPaperBackReq(requestIds);
        } catch (Exception e) {
        return AjaxResult.error(e.getMessage());
    }

        return toAjax(workRequestFundService.deleteWorkRequestFundByRequestIds(ids));
    }

    /**
     * 审核请款
     */
    @RequiresPermissions("work:fund:check")
    @Log(title = "审核请款", businessType = BusinessType.CHECK)
    @PostMapping("/check")
    @ResponseBody
    public AjaxResult check(String[] ids) {
        try {
            List<WorkRequestFund> list = workRequestFundService.selectWorkRequestFundByRequestIds(ids);
            if (list.stream().anyMatch(r -> !r.getRequestStatus().equals("1"))) {
                return AjaxResult.error("必须为未审核状态");
            }
            list.forEach(e -> {

                e.setRequestStatus("2");
                workRequestFundService.updateWorkRequestFund(e);
            });
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 审核请款
     */
    @RequiresPermissions("work:fund:grant")
    @Log(title = "打款请款", businessType = BusinessType.GRANT)
    @PostMapping("/grant")
    @ResponseBody
    public AjaxResult grant(String[] ids) {
        try {
            List<WorkRequestFund> list = workRequestFundService.selectWorkRequestFundByRequestIds(ids);
            if (list.stream().anyMatch(r -> !r.getRequestStatus().equals("2"))) {
                return AjaxResult.error("必须为已审核状态");
            }
            list.forEach(e -> {

                e.setRequestStatus("3");
                e.setPayTime(DateUtils.getNowDate());
                workRequestFundService.updateWorkRequestFund(e);
            });
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

}
